package com.common.config;

import com.google.common.collect.Lists;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @classDescription:
 * @author:xiayingjie
 * @createTime:16/8/16
 */
//@Configuration
//@EnableCaching
public class CompositeCacheConfig {


    //redis
    @Bean
    public CacheManager cacheManager(net.sf.ehcache.CacheManager cm,RedisTemplate redisTemplate){
        CompositeCacheManager cacheManager=new CompositeCacheManager();
        List<CacheManager> list= Lists.newArrayList();
        list.add(new EhCacheCacheManager(cm));
        list.add(new RedisCacheManager(redisTemplate));

        cacheManager.setCacheManagers(list);
        cacheManager.afterPropertiesSet();
        cacheManager.setFallbackToNoOpCache(true);

        return cacheManager;
    }


    @Bean
    public RedisConnectionFactory redisCF(){
        JedisConnectionFactory jcf=new JedisConnectionFactory();
        jcf.setPort(6379);
        jcf.afterPropertiesSet();//还不明白设么意思
        jcf.setUsePool(true);
        return  jcf;
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisCF){
        RedisTemplate redis=new RedisTemplate();
        redis.setConnectionFactory(redisCF);
        redis.afterPropertiesSet();
        return redis;
    }



    //创建echcache的CacheManager实例，因为是工厂(实现了FacotoryBean)
    @Bean
    public EhCacheManagerFactoryBean ehcache(){
        EhCacheManagerFactoryBean factoryBean=new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        return factoryBean;
    }





}
